// 网络通信管理模块

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const os = require('os');
const path = require('path');

class NetworkManager {
    constructor() {
        this.app = express();
        this.server = http.createServer(this.app);
        this.io = socketIo(this.server, {
            cors: {
                origin: "*",
                methods: ["GET", "POST"]
            }
        });
        
        this.port = 3000;
        this.isServerRunning = false;
        this.localIP = this.getLocalIP();
        this.sharedData = {
            userInfo: {
                name: '',
                department: '',
                position: ''
            },
            status: {
                name: '工作中',
                color: '#28a745',
                description: '正在专注工作'
            },
            tasks: []
        };
        
        this.setupRoutes();
        this.setupSocketEvents();
    }
    
    // 获取本地IP地址
    getLocalIP() {
        const interfaces = os.networkInterfaces();
        for (const name of Object.keys(interfaces)) {
            for (const networkInterface of interfaces[name]) {
                if (networkInterface.family === 'IPv4' && !networkInterface.internal) {
                    return networkInterface.address;
                }
            }
        }
        return 'localhost';
    }
    
    // 设置路由
    setupRoutes() {
        // 静态文件服务
        this.app.use(express.static(path.join(__dirname, '../public')));
        
        // API路由
        this.app.get('/api/status', (req, res) => {
            res.json({
                userInfo: this.sharedData.userInfo,
                status: this.sharedData.status,
                tasks: this.sharedData.tasks
            });
        });
        
        this.app.get('/api/user-info', (req, res) => {
            res.json(this.sharedData.userInfo);
        });
        
        this.app.get('/api/current-status', (req, res) => {
            res.json(this.sharedData.status);
        });
        
        this.app.get('/api/tasks', (req, res) => {
            res.json(this.sharedData.tasks);
        });
        
        // 主页路由
        this.app.get('/', (req, res) => {
            res.sendFile(path.join(__dirname, '../public/index.html'));
        });
    }
    
    // 设置Socket事件
    setupSocketEvents() {
        this.io.on('connection', (socket) => {
            console.log('新用户连接:', socket.id);
            
            // 发送当前共享数据
            socket.emit('shared-data-update', this.sharedData);
            
            // 监听数据更新请求
            socket.on('request-data-update', () => {
                socket.emit('shared-data-update', this.sharedData);
            });
            
            // 监听断开连接
            socket.on('disconnect', () => {
                console.log('用户断开连接:', socket.id);
            });
        });
    }
    
    // 启动服务器
    startServer() {
        return new Promise((resolve, reject) => {
            if (this.isServerRunning) {
                resolve({ port: this.port, ip: this.localIP });
                return;
            }
            
            this.server.listen(this.port, () => {
                this.isServerRunning = true;
                console.log(`服务器运行在 http://${this.localIP}:${this.port}`);
                resolve({ port: this.port, ip: this.localIP });
            }).on('error', (err) => {
                if (err.code === 'EADDRINUSE') {
                    // 端口被占用，尝试下一个端口
                    this.port++;
                    this.startServer().then(resolve).catch(reject);
                } else {
                    reject(err);
                }
            });
        });
    }
    
    // 停止服务器
    stopServer() {
        if (this.isServerRunning) {
            this.server.close(() => {
                this.isServerRunning = false;
                console.log('服务器已停止');
            });
            
            // 断开所有Socket连接
            this.io.close();
        }
    }
    
    // 更新共享数据
    updateSharedData(data) {
        if (data.userInfo) {
            this.sharedData.userInfo = { ...this.sharedData.userInfo, ...data.userInfo };
        }
        
        if (data.status) {
            this.sharedData.status = data.status;
        }
        
        if (data.tasks) {
            this.sharedData.tasks = data.tasks;
        }
        
        // 通知所有连接的客户端数据已更新
        this.io.emit('shared-data-update', this.sharedData);
    }
    
    // 获取服务器状态
    getServerStatus() {
        return {
            isRunning: this.isServerRunning,
            port: this.port,
            ip: this.localIP,
            url: this.isServerRunning ? `http://${this.localIP}:${this.port}` : null
        };
    }
    
    // 获取连接的客户端数量
    getClientCount() {
        return this.io.engine.clientsCount;
    }
}

// 导出单例实例
const networkManager = new NetworkManager();
module.exports = networkManager;